#include "PrecompiledHeader.h"
#include "IOcclusionTester.h"

/*--------------------------------------------------------------------------*/

IOcclusionTester::IOcclusionTester()
{
	this->m_occlusionQuery = 0;
	this->m_occlusionTestResult = 0;
	this->m_occlusionTestEnabled = true;
	this->m_queryStarted = false;

	glGenQueries(1, &this->m_occlusionQuery);
	AssertLogC(this->m_occlusionQuery == 0, "Failed to create OcclusionQuery");
}

/*--------------------------------------------------------------------------*/

IOcclusionTester::~IOcclusionTester()
{
	glDeleteQueries(1, &this->m_occlusionQuery);
}

/*--------------------------------------------------------------------------*/

void IOcclusionTester::StartOcclusionTest()
{
	if (this->m_occlusionTestEnabled)
	{
		uint hasBeenTested = 0;
		glGetQueryObjectuiv(this->m_occlusionQuery, GL_QUERY_RESULT_AVAILABLE, &hasBeenTested);

		if (hasBeenTested)
		{
			glGetQueryObjectuiv(this->m_occlusionQuery, GL_QUERY_RESULT, &this->m_occlusionTestResult);
		}

		glBeginQuery(GL_SAMPLES_PASSED, this->m_occlusionQuery);
		this->m_queryStarted = true;
	}
}

/*--------------------------------------------------------------------------*/

void IOcclusionTester::StopOcclusionTest()
{
	if (this->m_queryStarted && this->m_occlusionTestEnabled)
	{
		glEndQuery(GL_SAMPLES_PASSED);
		this->m_queryStarted = false;
	}
}

/*--------------------------------------------------------------------------*/

bool IOcclusionTester::GetOcclusionTestResult() const
{
	return this->m_occlusionTestEnabled == false || (this->m_occlusionTestEnabled && this->m_occlusionTestResult > 0);
}

/*--------------------------------------------------------------------------*/

bool IOcclusionTester::GetOcclusionTestEnabled() const
{
	return this->m_occlusionTestEnabled;
}

/*--------------------------------------------------------------------------*/

void IOcclusionTester::SetOcclusionTestEnabled(bool b)
{
	this->m_occlusionTestEnabled = b;
}

/*--------------------------------------------------------------------------*/